using Microsoft.UI.Windowing;
using Microsoft.UI;
using ymk_camera_surveillance.WinUI;
using System.Windows.Forms;
using Microsoft.Maui.Handlers;
using Application = Microsoft.Maui.Controls.Application;

namespace ymk_camera_surveillance.Views;

public partial class EscPage : ContentPage
{

    static public volatile int ESC_PAGE_OPENED = 0;
    private nint needCloseWin = 0;

    public EscPage(nint needCloseWin)
    {
        InitializeComponent();
        ESC_PAGE_OPENED += 1;
        this.needCloseWin = needCloseWin;

        Loaded += EscPage_Loaded;
        Unloaded += EscPage_Unloaded;
    }

    private void EscPage_Unloaded(object sender, EventArgs e)
    {
        ESC_PAGE_OPENED = 0;
    }

    private void EscPage_Loaded(object sender, EventArgs e)
    {
        var mauiWindow = this.Window;
        IntPtr hWnd = ((MauiWinUIWindow)mauiWindow.Handler.PlatformView).WindowHandle;
        WindowId myWndId = Win32Interop.GetWindowIdFromWindow(hWnd);
        var _appWindow = AppWindow.GetFromWindowId(myWndId);
        _appWindow.SetPresenter(AppWindowPresenterKind.Default);

        var displayInfo = DeviceDisplay.Current.MainDisplayInfo;
        mauiWindow.Width = displayInfo.Width / 4;
        mauiWindow.Height = displayInfo.Height / 4;
        mauiWindow.X = (displayInfo.Width / displayInfo.Density - Window.Width) / 2;
        mauiWindow.Y = (displayInfo.Height / displayInfo.Density - Window.Height) / 2;

    }

    private void cancel_Clicked(object sender, EventArgs e)
    {
        App.Current.CloseWindow(this.Window);
    }

    private async void exit_Clicked(object sender, EventArgs e)
    {
        await MainThread.InvokeOnMainThreadAsync(() =>
        {
            var windowsCount = Application.Current.Windows.Count;
            if (windowsCount > 2)
            {
                Win32.CloseWindow(needCloseWin);
                Application.Current.CloseWindow(this.Window);
            }
            else
            {
                App.KB_HOOK.Dispose();
                App.Current.Quit();
            }
        });
    }
}